import cv2
import numpy as np

# 读取图像
image = cv2.imread('../temp/image.jpg')
if image is None:
    print('Cannot read image file')
    exit(-1)

# 将图像转换为灰度图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# 对x方向进行Sobel滤波
grad_x = cv2.Sobel(gray, cv2.CV_16S, 1, 0, ksize=3)

# 对y方向进行Sobel滤波
grad_y = cv2.Sobel(gray, cv2.CV_16S, 0, 1, ksize=3)

# 将x方向滤波结果转换为8位无符号整数
abs_grad_x = cv2.convertScaleAbs(grad_x)

# 将y方向滤波结果转换为8位无符号整数
abs_grad_y = cv2.convertScaleAbs(grad_y)

# 将两个方向的滤波结果合并
grad = cv2.addWeighted(abs_grad_x, 0.5, abs_grad_y, 0.5, 0)

# 显示原始图像和Sobel滤波后的图像
cv2.namedWindow('Original Image', cv2.WINDOW_NORMAL)
cv2.namedWindow('Sobel Image', cv2.WINDOW_NORMAL)
cv2.imshow('Original Image', image)
cv2.imshow('Sobel Image', grad)

cv2.waitKey(0)
cv2.destroyAllWindows()
